package drds.plus.executor.function.scalar.string;

import drds.plus.common.utils.TStringUtil;
import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * <pre>
 * RPAD(str,len,padstr)
 *
 * Returns the string str, rightNode-padded with the string padstr to a length of len characters. If str is longer than len, the return value is shortened to len characters.
 *
 * mysql> SELECT RPAD('hi',5,'?');
 *         -> 'hi???'
 * mysql> SELECT RPAD('hi',1,'?');
 *         -> 'h'
 *
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月11日 下午6:23:39
 * @since 5.1.0
 */
public class Rpad extends ScalarFunction {

    public Type getReturnType() {
        return Type.StringType;
    }

    public String[] getFunctionNames() {
        return new String[]{"RPAD"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }
        String str = Type.StringType.convert(args[0]);
        Integer len = Type.IntegerType.convert(args[1]);
        String padStr = Type.StringType.convert(args[2]);

        if (len == str.length()) {
            return str;
        }

        if (len < 0) {
            return null;
        }
        if (len < str.length()) {
            return str.substring(0, len);
        }

        return TStringUtil.rightPad(str, len, padStr);

    }

}
